package com.oa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.oa.back.ResponseBack;
import com.oa.common.base.Page;
import com.oa.common.base.Pageable;
import com.oa.common.dto.PositionDto;
import com.oa.common.enums.CodeStatus;
import com.oa.dao.BaseDao;
import com.oa.dao.PositionDao;
import com.oa.entities.Position;
import com.oa.service.PositionService;
import com.oa.service.UndeleteServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class PositionServiceImpl extends UndeleteServiceImpl<Long,Position> implements PositionService {

    private static final Logger logger= LoggerFactory.getLogger(PositionServiceImpl.class);

    @Autowired
    private PositionDao dao;

    @Override
    protected BaseDao<Long, Position> getSelfDao() {
        return dao;
    }

    @Override
    public void setClass(Class<Position> clazz) {

    }

    @Override
    @Transactional
    public Page<Position> findPage(Pageable pageable, String key) {
        return dao.findPage(pageable,key);
    }

    @Override
    @Transactional
    public ResponseBack<String> submit(String params) {
        if (StringUtils.isEmpty(params)){
            return ResponseBack.fial(CodeStatus.PARAMS_FAIL.getResponseStatus());
        }
        try{
            PositionDto dto= JSONObject.parseObject(params,PositionDto.class);
            if (dto==null){
                return ResponseBack.fial(CodeStatus.PARAMS_FAIL.getResponseStatus());
            }
            if (StringUtils.isEmpty(dto.getName())){
                return ResponseBack.fial(CodeStatus.POSITION_NAME_NOTNULL.getResponseStatus());
            }
            if (validate(dto.getName(),null)){
                return ResponseBack.fial(CodeStatus.POSITION_EXIST.getResponseStatus());
            }
            Position parent= null;
            if (dto.getParentId()!=null){
               parent= get(dto.getParentId());
                if (parent==null){
                    return ResponseBack.fial(CodeStatus.POSITION_UNDERFUND.getResponseStatus());
                }
            }
            Position position= new Position();
            position.setContent(dto.getContent());
            position.setDate(System.currentTimeMillis());
            position.setName(dto.getName());
            if (parent!=null){
                position.setParent(parent);
            }
            save(position);
        }catch (RuntimeException ex){
            logger.error("上传岗位接口异常:",ex);
            return ResponseBack.fial(CodeStatus.SYSTEM_FAIL.getResponseStatus());
        }
        return ResponseBack.success(null);
    }

    @Override
    public Boolean validate(String name, Long id) {
        return dao.validate(name, id);
    }
}
